package com.example.glideprogressiveloadimg.util;

import java.io.IOException;
import java.io.InputStream;

public class StreamProcessor {

    /**
     * 最多消耗4个字节，并以int形式返回(考虑到字节长度)。
     * 指定的字节数不能被消耗， 则抛出异常
     * Consumes up to 4 bytes and returns them as int (taking into account endianess). Throws
     * exception if specified number of bytes cannot be consumed.
     *
     * @param is the input stream to read bytes from  字节输入流
     * @param numBytes the number of bytes to read  要读取的字节数， 取值范围 [1,2, 4]
     * @param isLittleEndian whether the bytes should be interpreted in little or big endian format
     *                       字节应该以小端还是大端格式解释 ,一般取值false
     * @return packed int read from input stream and constructed according to endianness
     *          返回 从输入流读取并根据端序构造的int类型
     */
    public static int readPackedInt(InputStream is, int numBytes, boolean isLittleEndian)
            throws IOException {
        int value = 0;
        for (int i = 0; i < numBytes; i++) {
            int b = is.read();
            if (b == -1) {
                throw new IOException("no more bytes");
            }
            if (isLittleEndian) {
                value |= (b & 0xFF) << (i * 8);
            } else {
                value = (value << 8) | (b & 0xFF);
            }
        }
        return value;
    }

}
